#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import login_required
from documents.models import Document, Item, ModuleTerm, ModulePart
from shared.helper import render_to_response
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
import settings
from django.forms.forms import Form
from documents.forms import ItemForm, DocumentForm
from documents.itemtype import ItemType
from link.forms import LinkForm
from link.models import Link
from django.http import Http404

@login_required
def link(request, item_id):
    """
    The link view redirects to the link
    """
    
    link = Link.objects.get(item__id=item_id)
    
    item = link.item
    
    item.views = item.views + 1
    item.save()
        
    if(item.activated == False):
        raise Http404
    
    return redirect(link.url)

@login_required
def add_document_link(request, module_part_id, module_term_id):
    """
    The add_document_link is a mixture of add_document and add_link
    It is treated like "Hey I've got a Link ready and there is no
    Document for this yet." But it also handles the case that there
    already exists a Document like this.
    """
    
    module_part = ModulePart.objects.get(id = module_part_id)
    module_term = ModuleTerm.objects.get(id = module_term_id)
    
    document = Document (
                         module_part = module_part,
                         module_term = module_term,
                         user = request.user
                        )
    
    if request.method == 'POST':
        document_form = DocumentForm(request.POST, instance = document)
        item_form = ItemForm(request.POST)
        link_form = LinkForm(request.POST)
        if document_form.is_valid() and item_form.is_valid() and link_form.is_valid():
            document = document_form.save()
            
            item = item_form.save(commit = False)
            item.document = document
            item.user = request.user
            item.item_type = ItemType.get_item_type_for_model(Link)
            item.save()
            
            link_form.instance.item = item
            link_form.save()
            
            return redirect(reverse('documents.views.module', kwargs={ 'module_term_id': module_term.id }))
    else:
        document_form = DocumentForm()
        item_form = ItemForm()
        link_form = LinkForm()
    
    return render_to_response(
                                request,
                                'link/add_document_link.html',
                                {
                                    'document_form': document_form,
                                    'item_form': item_form,
                                    'link_form': link_form,
                                    'module_part': module_part,
                                    'module_term': module_term
                                }
                             )

@login_required
def add_link(request, document_id):
    """
    The add_link view allows us to add a Link
    """

    # Get Upload context
    document = Document.objects.get(id = document_id)
    
    # Create the needed base for the Item
    item = Item(
                    document = document,
                    user = request.user,
                    item_type = ItemType.get_item_type_for_model(Link)
               )
    
    # If the form has already been filled in
    if request.method == 'POST':
        item_form = ItemForm(request.POST, instance = item)
        link_form = LinkForm(request.POST)
        if item_form.is_valid() and link_form.is_valid(): # All validation rules pass
            item = item_form.save()
            
            link_form.instance.item = item
            
            link_form.save()
            
            return redirect(reverse('documents.views.module', kwargs={ 'module_term_id': document.module_term.id }))
    
    # If the form has yet to be filled in
    else:
        item_form = ItemForm()
        link_form = LinkForm()
        
    return render_to_response(
                                request,
                                'link/add_link.html',
                                {
                                    'item_form': item_form,
                                    'link_form': link_form,
                                    'document': document,
                                }
                             )


@login_required
def delete_link(request, item_id):
    """
    View for deleting a link - allowed when you have delete right for links or are owner
    """
    
    link = Link.objects.get(item__id = item_id)
    
    # TODO: make use of item perms
    if not (request.user.has_perm('documents.delete_item') or request.user == link.item.user):
        return redirect(settings.LOGIN_URL)
    
    if request.method == 'POST':
        document = link.item.document
        link.item.delete()
        return redirect(reverse('documents.views.module', kwargs={ 'module_term_id': document.module_term.id }))
    
    form = Form()
    return render_to_response(
                                request,
                                'link/delete_link.html',
                                {
                                    'form': form,
                                    'link': link
                                }
                             )
    

@login_required
def change_link(request, item_id):
    """
    The change_link view allows us to change a Link - possible if you have the right, or are the owner
    """

    link = Link.objects.get(item__id = item_id)
    
    # TODO: make use of item perms
    if not (request.user.has_perm('item.change_item') or request.user == link.item.user):
        return redirect(settings.LOGIN_URL)
    
    # If the form has already been filled in
    if request.method == 'POST':
        item_form = ItemForm(request.POST, instance = link.item)
        link_form = LinkForm(request.POST, instance = link)
        if item_form.is_valid() and link_form.is_valid(): # All validation rules pass
            item_form.save()
            link_form.save();
            
            return redirect(reverse('documents.views.module', kwargs={ 'module_term_id': link.item.document.module_term.id }))
    
    # If the form has yet to be filled in
    else:
        item_form = ItemForm(instance = link.item)
        link_form = LinkForm(instance = link)
        
    return render_to_response(
                                request,
                                'link/change_link.html',
                                {
                                    'item_form': item_form,
                                    'link_form': link_form,
                                    'link': link,
                                }
                             )